<template>
  <div>
    <el-row>
      <el-col style="margin-top: 30px">
        <el-button
          type="primary"
          plain
          style="width: 20%"
          @click="dialogFormVisible1 = true"
          >新增文章</el-button
        >
        <!-- <el-button
          type="primary"
          plain
          style="width: 20%"
          @click="bt_2()"
          :class="{ 'active-button': reply === 2 }"
          >已回复</el-button
        > -->
      </el-col>

      <el-col style="margin-top: 10px">
        <el-table
          class="box-table"
          :data="Data"
          :stripe="true"
          :border="true"
          :fit="true"
          v-if="Data != null"
        >
          <el-table-column
            prop="title"
            label="文章标题"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="content"
            label="文章图示"
            width="auto"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <div style="width: 50%; height: 100px; margin: auto">
                <img :src="scope.row.photocontent" />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="articlecontent"
            label="文章链接"
            width="auto"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <a :href="scope.row.articlecontent">{{
                scope.row.articlecontent
              }}</a>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="auto"
          >
            <template #default="scope">
              <!-- <el-button
                style="color: green"
                link
                type="primary"
                size="small"
                @click="editGoods(scope.row)"
                >修改</el-button
              > -->
              <el-button
                link
                style="color: red"
                type="primary"
                size="small"
                @click="delBerbak(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col style="margin: 0 auto">
        <el-card>
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              :total="Total"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-col>

      <el-dialog
        title="文章修改"
        v-model="dialogFormVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-form :model="add" label-position="right">
          <el-form-item label="文章标题:" label-width="100px">
            <el-input v-model="add.messagetype"></el-input>
          </el-form-item>
          <el-form-item label="文章链接" label-width="100px">
            <el-input v-model="add.content"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="margin-top: 10px">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="新增文章"
        v-model="dialogFormVisible1"
        width="30%"
        :before-close="handleClose1"
      >
        <el-form :model="form">
          <el-form-item label="文章标题:" label-width="100px">
            <el-input v-model="form.messagetype"></el-input>
          </el-form-item>
          <el-form-item label="文章链接:" label-width="100px">
            <el-input
              v-model="form.content"
              placeholder="请填写公众号链接"
            ></el-input>
          </el-form-item>
        </el-form>
        <div>
          <!-- 显示图片的区域 -->
          <div v-if="imageUrl" style="margin: auto; width: 80%">
            <img :src="imageUrl" style="max-width: 100%; max-height: 300px" />
          </div>

          <!-- 图片选择按钮 -->
          <label for="fileInput" class="custom-button">上传图片</label>
          <input
            type="file"
            id="fileInput"
            accept="image/*"
            @change="handleFileChange"
          />
        </div>
        <div slot="footer" class="dialog-footer" style="margin-top: 10px">
          <el-button @click="dialogFormVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="submit_add">确 定</el-button>
        </div>
      </el-dialog>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRaw, onMounted, onBeforeMount } from "vue";
import apiService from "@/services/apiService";
import { v4 as uuidv4 } from "uuid";
import { Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "Liuyan"
});

//表格数据
const Data = ref<any>([
  // {
  //   messagetype: "测试",
  //   content: "https:111111"
  // }
]);
const currentPage = ref(1); // 当前页数
const pageSize = ref(10); // 每页条数
const Total = ref<number>(1); //总条数
const reply = ref<number>(1); //当前显示

//获取未回复表单数据
const GetList = () => {
  const params = {
    msgid: "PagingFindKnowledge",
    token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
    seq: uuidv4(),
    body: {
      pageno: currentPage.value,
      pagesize: pageSize.value,
      type: "科谱文章"
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // 使用 any 类型断言
      console.log(res.data);
      let arr = res.data.body.knowledges;

      Data.value = arr;
      Total.value = res.data.body.totalCount;
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};

// 监听页码变化
const handleCurrentChange = val => {
  currentPage.value = val;
  GetList();
};

// 监听每页条数变化
const handleSizeChange = val => {
  pageSize.value = val;
};

//删除
const delBerbak = (row: any) => {
  ElMessageBox.confirm("确认删除?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const params = {
        msgid: "DeleteKnowledgeArticle",
        token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
        seq: uuidv4(),
        body: {
          knowledgeId: row.id
        }
      };
      apiService.post("", params).then((res: any) => {
        console.log(res);
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功"
          });

          GetList();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

//新增文章
const dialogFormVisible1 = ref(false);
const add = ref<any>({
  messagetype: "",
  content: ""
});

// 组件的响应式数据
const imageUrl = ref<any>(""); // 用于显示图片的 URL
const base64Image = ref<string | null>(null); // 用于存储 Base64 图片数据
// 选择图片后触发的函数
const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement;
  const file = input.files?.[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = () => {
      // 显示图片
      imageUrl.value = reader.result as string;
      // 获取 Base64 字符串（去掉前缀部分）
      base64Image.value = (reader.result as string).split(",")[1];
    };

    reader.readAsDataURL(file);
  }
};
const submit_add = () => {
  if (
    imageUrl.value != "" &&
    form.value.messagetype != "" &&
    form.value.content != ""
  ) {
    ElMessageBox.confirm("确认新增该文章?", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        const params = {
          msgid: "AddKnowledgeArticle",
          token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
          seq: uuidv4(),
          body: {
            title: form.value.messagetype,
            contentUrl: form.value.content,
            coverBase64: base64Image.value,
            type: "png"
          }
        };
        apiService.post("", params).then((res: any) => {
          console.log(res);
          if (res.data.code == 200) {
            ElMessage({
              type: "success",
              message: "添加成功"
            });
            dialogFormVisible1.value = false;
            GetList();
          }
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除"
        });
      });
  } else {
    ElMessage({
      type: "error",
      message: "请填写完整上传信息"
    });
  }
};
//编辑回复
const dialogFormVisible = ref(false);
const form = ref<any>({
  messagetype: "",
  content: "",
  id: ""
});
const back = ref("");
const back_List = ref([]);
const editGoods = (row: any) => {
  console.log("回复");
  // form.messagetype = row.messagetype;
  // form.content = row.content;
  // form.id = row.id;
  // back_List.value = row.writemsgs;
  dialogFormVisible.value = true;
};

//回复按钮
const submit = () => {
  // ElMessageBox.confirm("确定修改吗?", "提示", {
  //   confirmButtonText: "确认",
  //   cancelButtonText: "取消",
  //   type: "warning"
  // })
  //   .then(() => {
  //     const utcDate = ref<any>();
  //     var date = new Date();
  //     utcDate.value = new Date(
  //       date.getTime() + date.getTimezoneOffset() * 60 * 1000
  //     );
  //     console.log(utcDate.value);
  //     const params = {
  //       msgid: "InsertWriteMsg",
  //       token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
  //       seq: uuidv4(),
  //       body: {
  //         leavemsgid: form.value.id,
  //         content: back.value,
  //         messagetypeid: 2,
  //         // fileid:'',
  //         createtime: utcDate.value
  //       }
  //     };
  //     apiService.post("", params).then((res: any) => {
  //       console.log(res);
  //       if (res.data.code == 200) {
  //         ElMessage({
  //           type: "success",
  //           message: "回复成功"
  //         });
  //         GetList();
  //         back.value = "";
  //         dialogFormVisible.value = false;
  //       }
  //     });
  //   })
  //   .catch(() => {
  //     ElMessage({
  //       type: "info",
  //       message: "取消回复"
  //     });
  //     dialogFormVisible.value = false;
  //   });
};
//关闭弹窗
const handleClose = (done: () => void) => {
  // ElMessageBox.confirm("确认关闭?")
  //   .then(() => {
  back.value = "";
  done();
  // })
  // .catch(() => {
  //   // catch error
  // });
};
const handleClose1 = (done: () => void) => {
  console.log("1");

  // ElMessageBox.confirm("确认关闭?")
  //   .then(() => {
  form.value = [];
  // imageUrl.value = "";
  done();
  // })
  // .catch(() => {
  //   // catch error
  // });
};

onMounted(() => {
  GetList();
});
</script>

<style lang="scss" scoped>
.active-button {
  background-color: #409eff;
  /* 设置按钮激活时的背景颜色 */
  color: white;
  /* 设置按钮激活时的文字颜色 */
}

/* 隐藏原生文件选择框 */
input[type="file"] {
  display: none;
}

/* 自定义按钮样式 */
.custom-button {
  display: inline-block;
  background-color: #409eff;
  color: white;
  padding: 10px 20px;
  font-size: 16px;
  border-radius: 5px;
  cursor: pointer;
  text-align: center;
  // margin-left: 30px;
  width: 100%;
}

/* 你可以根据需要调整输入框的布局 */
.file-upload-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
</style>
